package comms;

/**
 * Class which contains a number of Static methods and values which are
 * used to parse information from Strings which represent URIs for opening
 * communications objects.
 * 
 * @author Kevin
 */
public class URIParser {
	
	//Array index values.
	private static final int PROTOCOL_INDEX = 0;
	private static final int ADDRESS_INDEX = 1;
	private static final int PARAMS_INDEX = 2;
	
	//The URI delimiters.
	private static final char ADDRESS_DELIM = ':';
	private static final char PARAM_DELIM = ';';
	
	//Maximum number of tokens supported by this class.
	private static final int MAX_TOKENS = 3;

	/**
	 * Parses and returns the Protocol portion of a URI.
	 * 
	 * @param uri The URI to parse.
	 * @return The parsed protocol String.
	 * @throws URIException If an invalid URI.
	 */
	public static String getURIProtocol(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return tokens[PROTOCOL_INDEX];
	}
	
	/**
	 * Parses and returns the Address portion of a URI.
	 * 
	 * @param uri The URI to parse.
	 * @return The parsed address String.
	 * @throws URIException If an inavlid URI.
	 */
	public static String getURIAddress(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);

		if (tokens[ADDRESS_INDEX].equals("//")) {		
			return "";
		} else {
			System.out.println(tokens[ADDRESS_INDEX].substring(2));
			return tokens[ADDRESS_INDEX].substring(2);
		}
	}
	
	/**
	 * Parses and returns the Port/Params portion of a URI.
	 * 
	 * @param uri The URI to parse.
	 * @return The parsed Port/Params String.
	 * @throws URIException If an invalid URI.
	 */
	public static String getURIPortAsString(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return tokens[PARAMS_INDEX];
	}
	
	/**
	 * Parses and returns the Port portion of a URI as an integer.
	 * 
	 * @param uri The URI to parse.
	 * @return The port as an integer.
	 * @throws URIException If an invalid URI.
	 */
	public static int getURIPortAsInt(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return Integer.parseInt(tokens[PARAMS_INDEX]);
	}
	
	/**
	 * Tokenizes the passed String based on this classes delimiters and
	 * maximum tokens.
	 * <p>
	 * Returns the parsed data as an array of Strings.
	 * 
	 * @param uri The URI String to tokenize.
	 * @return The parsed Strings.
	 */
	private static String[] tokenizeURI(String uri) {
		String[] tokens = new String[MAX_TOKENS];
		StringBuffer buff = new StringBuffer(0);
		int i = 0;
		
		for (int j = 0; j < MAX_TOKENS; j++) {
			for ( ; (i < uri.length()) && ((uri.charAt(i) != ADDRESS_DELIM) && (uri.charAt(i) != PARAM_DELIM)); i++) {
				buff.append(uri.charAt(i));
			}
			
			i++;
			tokens[j] = buff.toString();
			buff.setLength(0);
		}
		
		return tokens;
	}
}
